<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="工位编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入工位编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="工位名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入工位名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="归属产线" prop="deptId">
        <treeselect style="width: 200px;" v-model="queryParams.deptId" :options="deptList" :flat="true"
                    :normalizer="normalizer" placeholder="选择归属产线"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:post:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['system:post:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['system:post:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="工位编号" align="center" prop="id"/>
      <el-table-column label="工位编码" align="center" prop="code"/>
      <el-table-column label="工位名称" align="center" prop="name"/>
      <el-table-column label="归属产线" align="center" prop="deptName"/>
      <el-table-column label="段别" align="center" prop="segmentName"/>
      <el-table-column label="IoT设备ID" align="center" prop="boxId"/>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="LCD展示" align="center" prop="showLcd">
        <template v-slot="scope">
          <span>{{ scope.row.showLcd ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否考勤" align="center" prop="ifAttendance">
        <template v-slot="scope">
          <span>{{ scope.row.ifAttendance ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:post:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:post:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改工位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工位名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入工位名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工位编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入编码名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="段别" prop="segmentId">
              <el-select v-model="form.segmentId" placeholder="请选择段别" filterable style="width: 100%"
                         @change="handleSegmentChange">
                <el-option v-for="item in segmentList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="IoT设备ID" prop="boxId">
              <el-input v-model="form.boxId" placeholder="请输入IoT设备ID"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="归属产线" prop="deptId" required>
              <treeselect v-model="form.deptId" :options="deptList" :flat="true" :normalizer="normalizer"
                          placeholder="选择归属产线"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工位顺序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工位状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusDictDatas" :key="parseInt(dict.value)" :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="LCD展示">
              <el-radio-group v-model="form.showLcd">
                <el-radio :key="true" :label="true">是</el-radio>
                <el-radio :key="false" :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否考勤">
              <el-radio-group v-model="form.ifAttendance">
                <el-radio :key="true" :label="true">是</el-radio>
                <el-radio :key="false" :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listPost, getPost, delPost, addPost, updatePost, exportPost, delPostList} from "@/api/system/post";
import {listDept} from "@/api/system/dept";
import * as SegmentApi from '@/api/lamp/segment';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {CommonStatusEnum} from '@/utils/constants'
import {getDictDatas, DICT_TYPE} from '@/utils/dict'

// 在组件定义前添加 props
export default {
  name: 'PostComponent',
  components: {Treeselect}, // 添加这一行，注册Treeselect组件
  props: {
    deptId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      deptList: [],
      segmentList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 选中行
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        code: undefined,
        name: undefined,
        deptId: undefined // 添加 deptId 作为查询参数
      },
      // 表单参数
      form: {
        id: undefined,
        code: undefined,
        name: undefined,
        sort: 0,
        status: CommonStatusEnum.ENABLE,
        remark: undefined,
        showLcd: false,
        ifAttendance: false,
        segmentId: undefined,
        segmentName: undefined,
        boxId: undefined
      },
      // 表单校验
      rules: {
        name: [
          {required: true, message: "工位名称不能为空", trigger: "blur"}
        ],
        code: [
          {required: true, message: "工位编码不能为空", trigger: "blur"}
        ],
        sort: [
          {required: true, message: "工位顺序不能为空", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: "请选择归属产线", trigger: "blur"}
        ],
        segmentId: [
          {required: true, message: "请选择段别", trigger: "blur"}
        ],
        boxId: [
          {required: true, message: "请输入IoT设备ID", trigger: "blur"}
        ]
      },

      // 枚举
      CommonStatusEnum: CommonStatusEnum,
      // 数据字典
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS)
    };
  },
  created() {
    // 如果有传入 deptId，则设置查询条件
    if (this.deptId) {
      this.queryParams.deptId = this.deptId;
    }
    this.getList();
    this.getOptions();
  },
  watch: {
    // 添加watch监听deptId变化
    deptId: {
      handler(newValue) {
        if (newValue) {
          this.queryParams.deptId = newValue;
          this.getList(); // 重新查询数据
        }
      },
      immediate: true
    }
  },
  methods: {
    getOptions() {
      listDept(this.queryParams).then(response => {
        this.deptList = this.addLevelToNodes(this.handleTree(response.data, "id"), 1);
        this.deptList = this.deptList[0].children
        console.log(this.deptList);
        this.loading = false;
      });

      // 获取段别列表
      SegmentApi.getSegmentPage({pageSize: 100, pageNo: 1}).then(response => {
        this.segmentList = response.data.list;
      }).catch(error => {
        this.$message.error('获取段别列表失败');
      });
    },

    // 处理段别选择变化
    handleSegmentChange(value) {
      const selectedSegment = this.segmentList.find(item => item.id === value);
      if (selectedSegment) {
        this.form.segmentName = selectedSegment.name;
      } else {
        this.form.segmentName = undefined;
      }
    },

    // 递归函数为节点添加层级标记
    // 递归函数为节点添加层级标记
    addLevelToNodes(nodes, currentLevel = 1) {
      if (!nodes || !Array.isArray(nodes)) {
        return [];
      }
      return nodes.map(node => {
        const newNode = {
          ...node,
          level: currentLevel
        };
        if (node.children && node.children.length > 0) {
          newNode.children = this.addLevelToNodes(node.children, currentLevel + 1);
        }
        return newNode;
      });
    },
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };

      // 关键：如果不是第三级节点，则禁用
      if (node.deptType !== 3) {
        normalizedNode.isDisabled = true; // 修改为 isDisabled
      } else {
      }
      return normalizedNode;
    },
    /** 查询工位列表 */
    getList() {
      this.loading = true;
      listPost(this.queryParams).then(response => {
        this.postList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        code: undefined,
        name: undefined,
        sort: 0,
        status: CommonStatusEnum.ENABLE,
        remark: undefined,
        showLcd: false,
        ifAttendance: false,
        segmentId: undefined,
        segmentName: undefined,
        boxId: undefined
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const deptId = this.deptId || this.queryParams.deptId; // 保留deptId
      this.resetForm("queryForm");
      if (deptId) {
        this.queryParams.deptId = deptId;
      }
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getPost(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工位";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updatePost(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除工位编号为"' + ids + '"的数据项?').then(function () {
        return delPost(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 批量删除操作 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认批量删除选中的工位数据?')
      try {
        await delPostList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 选择行数据 */
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有工位数据项?').then(() => {
        this.exportLoading = true;
        return exportPost(queryParams);
      }).then(response => {
        this.$download.excel(response, '工位数据.xls');
      }).finally(() => {
        this.exportLoading = false;
      });
    }
  }
};
</script>
